package com.itheima.reggie.controller.front;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.constant.CommonConstant;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.AliyunSmsUtil;
import com.itheima.reggie.util.IpUtil;
import com.itheima.reggie.util.LoginUserUtil;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 前端用户controller
 */
@RestController
@RequestMapping("/fronts/user")
@Slf4j
public class UserController {

    @Autowired
    private AliyunSmsUtil aliyunSmsUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private LoginUserUtil loginUserUtil;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信服务API完成发送短信
            aliyunSmsUtil.sendSms(phone,code);
            //需要将生成的验证码保存到Session
            session.setAttribute(phone,code);
            return Result.success("手机验证码短信发送成功");
        }
        return Result.error("短信发送失败");
       // return Result.success("手机验证码短信发送成功");
    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody JSONObject map, HttpSession session){
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();

        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code))
        {
            return Result.error("手机号或验证码不能为空");
        }

        //从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if(codeInSession != null && code.equals(codeInSession.toString())){
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.removeAttribute(phone);
           // session.setAttribute(CommonConstant.FRONTUSER,user.getId());
            loginUserUtil.setFrontUser(user.getId(),30L);
            return Result.success(user);
        }
        return Result.error("登录失败");
    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
//    @PostMapping("/login")
//    public Result<User> login1(@RequestBody JSONObject map, HttpSession session){
//        log.info(map.toString());
//        //获取手机号
//        String phone = map.get("phone").toString();
//        //获取验证码
//        String code = map.get("code").toString();
//
//        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code))
//        {
//            return Result.error("手机号或验证码不能为空");
//        }
//
//
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(User::getPhone,phone);
//
//        User user = userService.getOne(queryWrapper);
//        if(user == null){
//            //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
//            user = new User();
//            user.setPhone(phone);
//            user.setStatus(1);
//            userService.save(user);
//        }
//        session.removeAttribute(phone);
//        session.setAttribute(CommonConstant.FRONTUSER,user.getId());
//        return Result.success(user);
//    }




    /**
     * 用户退出
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(){
        //清理Session中保存的当前登录员工的id
        //request.getSession().removeAttribute(CommonConstant.FRONTUSER);
        loginUserUtil.removeFrontUser(null);
        return Result.success("退出成功");
    }
}
